import { using } from 'bluebird';
import * as Redlock from 'redlock';
import * as redis from 'redis';
import { config } from '../config';

export const redisClient = redis.createClient(config.redisConfig.port, config.redisConfig.host);
const redlock = new Redlock(
    // you should have one client for each independent redis node
    // or cluster
    [redisClient],
    {
        // the expected clock drift; for more details
        // see http://redis.io/topics/distlock
        driftFactor: 0.01, // time in ms

        // the max number of times Redlock will attempt
        // to lock a resource before erroring
        retryCount: 10,

        // the time in ms between attempts
        retryDelay: 200, // time in ms

        // the max time in ms randomly added to retries
        // to improve performance under high contention
        // see https://www.awsarchitectureblog.com/2015/03/backoff.html
        retryJitter: 200 // time in ms
    }
);
const unlockErrorHandler = function (err) {
    //console.error('A redis error has occurred:', err);
    throw new Error(err);
}

export function UsingLock(key: string, action: Function): any {
    return using(redlock.disposer(key, 1000, unlockErrorHandler), (function (lock) {
        return action();
    }));
}